import subprocess
import json
from PyQt5.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout,
                             QPushButton, QTextEdit, QFileDialog, QMessageBox)

class MetadataViewerUI(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("视频元数据查看器")
        self.setGeometry(100, 100, 600, 400)

        # 初始化UI元素
        self.video_path = None
        self.init_ui()

    def init_ui(self):
        # 主窗口布局
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        layout = QVBoxLayout()

        # 视频选择按钮
        self.select_btn = QPushButton("选择视频文件")
        self.select_btn.clicked.connect(self.select_video)
        layout.addWidget(self.select_btn)

        # 显示元数据的文本框
        self.result_text = QTextEdit()
        self.result_text.setReadOnly(True)
        layout.addWidget(self.result_text)

        # 执行按钮
        self.run_btn = QPushButton("获取元数据")
        self.run_btn.clicked.connect(self.get_metadata)
        layout.addWidget(self.run_btn)

        central_widget.setLayout(layout)

    def select_video(self):
        file_path, _ = QFileDialog.getOpenFileName(self, "选择视频文件", "", "视频文件 (*.mp4 *.avi)")
        if file_path:
            self.video_path = file_path
            QMessageBox.information(self, "提示", f"已选择视频: {file_path}")

    def get_metadata(self):
        """调用ffprobe命令获取视频元数据并添加详细注释 | Call ffprobe to get video metadata with detailed comments"""
        if not self.video_path:
            QMessageBox.warning(self, "警告", "请先选择视频文件 | Please select a video file first")
            return

        try:
            # 调用ffprobe获取JSON格式的元数据 | Call ffprobe to get metadata in JSON format
            result = subprocess.run(
                ["ffprobe", "-v", "quiet", "-print_format", "json", "-show_format", "-show_streams", self.video_path],
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                text=True
            )
            metadata = json.loads(result.stdout)

            # 添加注释说明
            def add_comments(data, indent=0):
                comments = ""
                if isinstance(data, dict):
                    comments += "{\n"
                    for key, value in data.items():
                        comments += " " * (indent + 2) + f'"{key}": '  # 字段名
                        # 常见字段注释
                        if key == "filename":
                            comments += f'"{value}",  // 视频文件名\n'
                        elif key == "format_name":
                            comments += f'"{value}",  // 容器格式（如mp4、avi等）\n'
                        elif key == "duration":
                            comments += f'"{value}",  // 视频总时长（秒）\n'
                        elif key == "size":
                            comments += f'"{value}",  // 文件大小（字节）\n'
                        elif key == "bit_rate":
                            comments += f'"{value}",  // 平均比特率（bps）\n'
                        elif key == "codec_name":
                            comments += f'"{value}",  // 编码格式（如h264、aac等）\n'
                        elif key == "width":
                            comments += f'"{value}",  // 视频宽度（像素）\n'
                        elif key == "height":
                            comments += f'"{value}",  // 视频高度（像素）\n'
                        elif key == "sample_rate":
                            comments += f'"{value}",  // 音频采样率（Hz）\n'
                        elif key == "channels":
                            comments += f'"{value}",  // 音频声道数\n'
                        elif key == "avg_frame_rate":
                            comments += f'"{value}",  // 平均帧率（帧/秒）\n'
                        elif key == "profile":
                            comments += f'"{value}",  // 编码配置文件\n'
                        elif key == "pix_fmt":
                            comments += f'"{value}",  // 像素格式\n'
                        elif key == "disposition":
                            comments += f'"{value}",  // 流属性配置\n'
                        elif key == "tags":
                            comments += f'"{value}",  // 附加标签信息\n'
                        else:
                            if isinstance(value, (dict, list)):
                                comments += add_comments(value, indent + 2)
                            else:
                                comments += f'"{value}",  // 其他字段\n'
                    comments += " " * indent + "}"
                elif isinstance(data, list):
                    comments += "[\n"
                    for item in data:
                        comments += " " * (indent + 2) + add_comments(item, indent + 2) + ",\n"
                    comments += " " * indent + "]"
                return comments

            formatted_metadata = "带注释的视频元数据：\n"
            formatted_metadata += add_comments(metadata)
            self.result_text.setText(formatted_metadata)
        except FileNotFoundError:
            QMessageBox.critical(self, "错误",
                                 "未找到ffprobe，请确保已安装FFmpeg并添加到系统路径中。 | ffprobe not found, please ensure FFmpeg is installed and in system PATH.")
        except json.JSONDecodeError:
            QMessageBox.critical(self, "错误",
                                 "无法解析元数据，请检查视频文件是否有效。 | Failed to parse metadata, please check if the video file is valid.")


if __name__ == '__main__':
    app = QApplication([])
    window = MetadataViewerUI()
    window.show()
    app.exec_()
